﻿namespace Leetcode.N0025;
public class Solution
{
    public ListNode ReverseKGroup(ListNode head, int k)
    {
        var preHead = new ListNode(0, head);

        var from = preHead;

        while (from.next != null)
        {
            ListNode to = from;
            for (int i = 0; i < k; i++)
            {
                to = to.next;
                if (to == null)
                {
                    return preHead.next;
                }
            }
            from = this.ReverseNode(from, to);
        }

        return preHead.next;
    }

    private ListNode ReverseNode(ListNode from, ListNode to)
    {
        var first = from.next;
        var cur = first;
        var pre = to.next;
        from.next = to;
        while (pre != to)
        {
            var next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return first;
    }
}
